<?php

namespace apps\user\models;

use Yii;
use yii\helpers\Security;
use yii\db\ActiveRecord;
use yii\db\Expression;

/**
 * This is the model class for table "user_user".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $access_token
 * @property string $email
 * @property string $mobile
 * @property integer $status
 * @property integer $role_id
 * @property string $create_time
 * @property string $update_time
 * @property string $active_code
 * @property string $active_time
 * @property string $last_login_time
 * @property string $last_login_ip
 */
class User extends ActiveRecord implements \yii\web\IdentityInterface {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'user_user';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['username', 'auth_key', 'password_hash'], 'required'],
            [['status', 'role_id'], 'integer'],
            [['create_time', 'update_time', 'active_code', 'active_time', 'last_login_time'], 'safe'],
            [['username'], 'string', 'max' => 20],
            [['auth_key', 'password_reset_token', 'access_token'], 'string', 'max' => 32],
            [['password_hash', 'email', 'mobile', 'last_login_ip'], 'string', 'max' => 255],
            [['username'], 'unique']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'username' => '用户名',
            'auth_key' => '身份码',
            'password_hash' => '密码',
            'password_reset_token' => '密码重置令牌',
            'access_token' => '访问令牌',
            'email' => '邮箱',
            'mobile' => '手机号码',
            'status' => '状态',
            'role_id' => '角色编号',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'active_code' => '激活码',
            'active_time' => '激活时间',
            'last_login_time' => '最后登录时间',
            'last_login_ip' => '最后登录IP',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery 
     */
    public function getRole() {
        return $this->hasOne(Role::className(), ['id' => 'role_id']);
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
                ],
                'value' => new Expression('NOW()'),
            ],
        ];
    }

    /**
     * Creates a new user
     *
     * @param  array       $attributes the attributes given by field => value
     * @return static|null the newly created model, or null on failure
     */
    public static function create($attributes) {
        /** @var User $user */
        $user = new static();
        $user->setAttributes($attributes);
        $user->setPassword($attributes['password']);
        $user->generateAuthKey();
        if ($user->save()) {
            return $user;
        } else {
            return null;
        }
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username) {
        return static::find(['username' => $username, 'status' => 1]);
    }

    /**
     * Finds an identity by the given ID. 
     * 
     * @param string|integer $id the ID to be looked for 
     * @return IdentityInterface|null the identity object that matches the given ID. 
     */
    public static function findIdentity($id) {
        return static::find($id);
    }

    /**
     * Finds an identity by the given token. 
     * 
     * @param string $token the token to be looked for 
     * @return IdentityInterface|null the identity object that matches the given token. 
     */
    public static function findIdentityByAccessToken($token) {
        return static::find(['access_token' => $token]);
    }

    /**
     * Finds user by password reset token
     *
     * @param  string      $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token) {
        $expire = \Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        if ($timestamp + $expire < time()) {
            // token expired
            return null;
        }
        return static::find([
                    'password_reset_token' => $token,
                    'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * @return int|string current user ID 
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @return string current user auth key 
     */
    public function getAuthKey() {
        return $this->auth_key;
    }

    /**
     * @param string $authKey 
     * @return boolean if auth key is valid for current user 
     */
    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password) {
        return Security::validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password) {
        $this->password_hash = Security::generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey() {
        $this->auth_key = Security::generateRandomKey();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken() {
        $this->password_reset_token = Security::generateRandomKey() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken() {
        $this->password_reset_token = null;
    }

}
